package com.nd.android.u.ui.activity.message_chat;

import ims.utils.CommUtil;
import ims.utils.IMLogUtils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import com.common.StarAppCIConst;
import com.common.StarAppConfig;
import com.common.StarAppConst.FRIEND_STATE;
import com.common.bean.EventBusBean;
import com.nd.android.u.chatInterfaceImpl.ChatInterfaceImpl;
import com.nd.android.u.controller.ChatConst;
import com.nd.android.u.controller.ChatConst.LocalMessageType;
import com.nd.android.u.ui.ChatEntry;
import com.nd.android.u.ui.R;
import com.nd.android.u.ui.chatUiUtils.ChatViewUtil;
import com.nd.android.u.ui.widge.ChatAddFriendView;
import com.nd.android.u.ui.widge.chatfragment.BottomFragment.CommonBottomListener;
import com.product.android.business.ApplicationVariable;
import com.product.android.commonInterface.BaseCommonStruct;
import com.product.android.commonInterface.CIConst;
import com.product.android.commonInterface.CommonInterfaceManager;
import com.product.android.utils.SharedPreferenceHelper;

import de.greenrobot.event.EventBus;

/**
 * 个人消息界面 <br>
 * Created 2014-7-26 下午4:37:12
 * 
 * @version
 * @author cb
 * @see
 */
public class ChatActivity_Person extends BaseChatMessageActivity implements
		CommonBottomListener {

	private ChatAddFriendView mAddFriendView;

	/** 是否是好友 */
	private boolean mIsFriend = false;

	/** 是否第一次加载 */
	private boolean mIsFirst = true;
	/** 是否第一次加载时网络断开过 */
	private boolean mIsNetError = false;

	/** 网络状态广播监听 */
	private BroadcastReceiver mNetStateReceiver = new NetStateReceiver();

    /**是否锁屏*/
    private boolean mIsScreenOff = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		EventBus.getDefault().register(this, BaseCommonStruct.class);
		EventBus.getDefault().register(this, String.class);
		EventBus.getDefault().register(this, View.class);
		EventBus.getDefault().register(this, EventBusBean.class);
		registerReceiver(mNetStateReceiver, new IntentFilter(
				ConnectivityManager.CONNECTIVITY_ACTION));

        final IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(mBatInfoReceiver, filter);
    }

	@Override
	protected boolean getParam(Bundle bundle) {
		messageType = LocalMessageType.PERSON;
		try {
			generalId = bundle.getLong(ChatConst.KEY.FID);
			// 获取好友的多点登陆状态
			name = ChatInterfaceImpl.INSTANCE.chatCallOtherModel
					.getUserName(generalId);
		} catch (Exception e) {
			finish();
			e.printStackTrace();
			return false;
		}
		if (bundle.containsKey(ChatConst.KEY.REPOST_DATA)) {
			repostMsgId = bundle.getString(ChatConst.KEY.REPOST_DATA);
			if (TextUtils.isEmpty(repostMsgId)) {
				IMLogUtils.e(IMLogUtils.CHAT, "get transmit key empty");
				finish();
				return false;
			}
		}
		if (bundle.containsKey("quick_reply_type")) {
			mQuickReplyType = bundle.getInt("quick_reply_type");
		}
		// if (TextUtils.isEmpty(name)) {
		// // 如果没有传联系人的名称过来，直接去取
		// name =
		// ChatInterfaceImpl.INSTANCE.chatCallOtherModel.getUserName(generalId);
		// }
		return true;
	}

	@Override
	public void createPopQuickReply() {
		mBottomFragment.dismisswidge();
		createPopQuickReply(generalId);
	}

	@Override
	public void showPopQuickReply(int width, int hight) {
		if (mPopQuickReply == null) {
			createPopQuickReply(getIntent().getIntExtra(ChatConst.KEY.FID, 0));
		}
		mPopQuickReply.show(findViewById(CONTENT_CONTAINER_ID), width, hight);
		
	}

	@Override
	protected void addDefaultFragment() {
		super.addDefaultFragment();
		initBottomView();
	}

	@Override
	public void onClickSwitchBtn() {

	}

	@Override
	public void onResume() {
		super.onResume();
		// 显示添加好友的提示
		if (!mIsScreenOff) {
//			mIsScreenOff = true;
			showAddFriend();
		}
		String newName = ChatInterfaceImpl.INSTANCE.chatCallOtherModel
				.getUserName(generalId);
		if (!TextUtils.isEmpty(newName)) {
			name = newName;
			mActivityTitle.setTitleText(name);
			ChatViewUtil
					.notifyChatItemAttributionChange(
							generalId,
							name,
							com.product.android.commonInterface.chat.ChatConst.CHAT_TYPE_PERSON);
		}
		mMessageListFragment.refreshChatItemShow();
	}

	
	/**
	 * @函数名称 :isNeedShowAddFriend
	 * @brief 显示添加好友的提示
	 * @see
	 * @since Ver 1.1
	 * @return
	 * @作者 : Administrator
	 * @创建时间 : 2014-6-4下午3:34:54
	 */
	private void showAddFriend() {
		SharedPreferenceHelper helper = SharedPreferenceHelper.getInstance();
		long self = ApplicationVariable.INSTANCE.getOapUid();
		String key = SharedPreferenceHelper.CONFIG_REMIND_FRIEND + self;
		final String nowValue = "," + generalId + ",";
		final String existValue = helper.loadKey(key);

		if (!CommUtil.JudgeNetWorkStatus(this)) {
			if (mIsFirst) {
				mIsNetError = true;
			}
		}

		// 先设置为不可点
		mActivityTitle.hideRightBtn();
		mActivityTitle.setRightBtnEnabel(false);

		new Thread(new Runnable() {
			public void run() {
                mIsNetError = false;
                boolean isStarMsg = (generalId != 0 && String.valueOf(generalId).equals(StarAppConfig.getConfig(StarAppConfig.JAY_UID)));

                if (isStarMsg) {
                    mIsFriend = true;
                } else {
                    mIsFriend = ChatInterfaceImpl.INSTANCE.chatCallOtherModel
                            .checkUidIsMyFolling(ChatActivity_Person.this,
                                    generalId);
                }

                if (mIsFriend) {
                    // 已经是好友，不显示

					runOnUiThread(new Runnable() {
						public void run() {
							mActivityTitle.showRightBtn();
							mActivityTitle.setRightBtnEnabel(true);

							if (mAddFriendView == null) {
								mAddFriendView = (ChatAddFriendView) findViewById(R.id.viewAddFriend);
							}
							mAddFriendView.setVisibility(View.GONE);
							mAddFriendView.postInvalidate();
						}
					});
				} else {
					runOnUiThread(new Runnable() {
						public void run() {
							if (mAddFriendView == null) {
								mAddFriendView = (ChatAddFriendView) findViewById(R.id.viewAddFriend);
							}
							if (existValue.indexOf(nowValue) > -1) {
								// 已经显示过添加好友提示，直接返回
								mAddFriendView.setVisibility(View.GONE);
								mAddFriendView.postInvalidate();
								return;
							}
							mActivityTitle.hideRightBtn();
							mActivityTitle.setRightBtnEnabel(false);
							mAddFriendView.setUid(generalId, name);
							mAddFriendView.setVisibility(View.VISIBLE);
							mAddFriendView.unRemind();
							mAddFriendView.postInvalidate();
						}
					});
				}

			}
		}).start();
	}



	@Override
	public void rightBtnHandle() {
		if (mIsFriend) {
			ChatEntry.INSTANCE.chatCallOtherModel_UI.gotoChatPrivateActivity(
					ChatActivity_Person.this, generalId);
		} else {
			ChatEntry.INSTANCE.chatCallOtherModel_UI
					.gotoPersonalDynamicActivity(ChatActivity_Person.this,
							generalId);
		}
	}

	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this, String.class);
		EventBus.getDefault().unregister(this, BaseCommonStruct.class);
		EventBus.getDefault().unregister(this, View.class);
		EventBus.getDefault().unregister(this, EventBusBean.class);
		if (mNetStateReceiver != null) {
			unregisterReceiver(mNetStateReceiver);
		}
        if(mBatInfoReceiver!=null){
            unregisterReceiver(mBatInfoReceiver);
        }
		super.onDestroy();
	}

	/**
	 * 添加好友
	 * 
	 * <br>
	 * Created 2014-11-4 上午11:13:29
	 * 
	 * @param obj
	 * @author : HuangYK
	 */
	public void onEventMainThread(String result) {
		if (result.equals(FRIEND_STATE.DO_ADD_FRIEND_SUCCESS)
				|| result.equals(FRIEND_STATE.ALREADY_IS_FRIEND)
				|| result.equals(FRIEND_STATE.DO_DELETE_FRIEND_SUCCESSFUL)) {
			// 添加好友，删除好友事件后都重新刷新数据
			mAddFriendView.setVisibility(View.GONE);
			mActivityTitle.showRightBtn();
			mActivityTitle.setRightBtnEnabel(true);
		}
	}
	
	/**
	 * EventBus接收函数
	 * 
	 * <br>
	 * Created 2014-10-29 下午4:07:30
	 * 
	 * @param struct
	 *            传递的数据
	 * @author : ChuXY
	 */
	public void onEventMainThread(BaseCommonStruct struct) {
		if (struct != null && struct.bPara && !TextUtils.isEmpty(struct.sPara)) {
			name = struct.sPara;
			mActivityTitle.setTitleText(name);
		}
	}
	

	/**
	 * EventBus接收函数
	 * 
	 * <br>
	 * Created 2014-10-29 下午4:07:30
	 * 
	 * @param bean
	 *            传递的数据
	 * @author : ChuXY
	 */
	public void onEventMainThread(EventBusBean bean) {
		if (bean != null && bean.hasValue(FRIEND_STATE.DO_ADD_FRIEND_SUCCESS)) {
			Object object=bean.getValue(FRIEND_STATE.DO_ADD_FRIEND_SUCCESS);
			if (object != null
					&& object instanceof Long) {
				long id=(Long)object;
				if(id==generalId){
					mIsFriend=true;
					if (mAddFriendView == null) {
						mAddFriendView = (ChatAddFriendView) findViewById(R.id.viewAddFriend);
					}
					if(mAddFriendView.getVisibility()==View.VISIBLE){
						mAddFriendView.setVisibility(View.GONE);
						mAddFriendView.postInvalidate();
					}
                    if(mActivityTitle!=null){
                        mActivityTitle.showRightBtn();
                        mActivityTitle.setRightBtnEnabel(true);
                    }
				}
			}
		}
	}
	
	/**
	 * 重绘界面后的通知
	 * 
	 * <br>
	 * Created 2014-11-4 上午11:13:29
	 * 
	 * @param obj
	 * @author : HuangYK
	 */
	public void onEventMainThread(View view) {
		mMessageListFragment.scrollToBottom(true);
		
	}

	/**
	 * 网络状态广播监听
	 * 
	 * <br>
	 * Created 2014-8-7 上午11:52:08
	 * 
	 * @version ChatActivity_Person
	 * @author HuangYK
	 * 
	 * @see
	 */
	private class NetStateReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// 网络状态改变
			if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent
					.getAction())) {

				ConnectivityManager connMgr = (ConnectivityManager) context
						.getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
				if (networkInfo != null) {
					mIsFirst = false;
					if (mIsNetError) {
						showAddFriend();
					}
				} else {
					// 网络断开
					return;
				}
			}
		}
	}


    /**
     * 锁屏监听
     *
     * <br>
     * Created 2014-8-7 上午11:52:08
     *
     * @version ChatActivity_Person
     * @author HuangYK
     *
     * @see
     */
    private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            final String action = intent.getAction();
            if(Intent.ACTION_SCREEN_ON.equals(action)){
                //解屏
                return;
            }

            if(Intent.ACTION_SCREEN_OFF.equals(action)){
                //锁屏
                mIsScreenOff = true;
                return;
            }
        }
    };


    /**
	 * 更新聊天界面顶部Title文字<br/>
	 * 修复BUG #58071 【仿真1】【朋友】 聊天界面上方显示的昵称，与实际的昵称不同，见图。 <br>
	 * Created 2014-11-7 下午8:05:23
	 * 
	 * @param message
	 * @author CYP
	 */
	@Override
	protected void processOtherMessageNotify(final Message message) {
		if (message != null
				&& message.what == StarAppCIConst.CHAT_NOTIFY_USER_NAME
				&& message.obj instanceof String
				&& !TextUtils.isEmpty((String) message.obj)) {
			Bundle bundle = message.getData();
			if (bundle != null) {
				long friendId = bundle
						.getLong(com.nd.android.u.controller.ChatConst.KEY.FID);
				if (friendId == getIntent().getExtras().getLong(
						ChatConst.KEY.FID)) {
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							mActivityTitle.setTitleText((String) message.obj);
							mActivityTitle.postInvalidate();
						}
					});
					
				}
			}
		}
	}
}
